package com.mmlc.utils;

import android.annotation.SuppressLint;
import android.app.Activity;

import com.mmlc.meimei.lichengkongjian.App;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2016/8/17.
 */
public class ActivityManager {

    public static void addActivity(Activity activity) {
        App.activityMap.put(activity.getClass().getSimpleName(), activity);
    }

    public static void exit() {
//        Set<Map.Entry<String, Activity>> entries = App.activityMap.entrySet();
//        Iterator<Map.Entry<String, Activity>> iterator = entries.iterator();
//        while (iterator.hasNext()) {
//            Map.Entry<String, Activity> next = iterator.next();
//            try {
//                next.getValue().finish();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        Map<String, Activity> map = App.activityMap;
        Iterator<String> iterator = App.activityMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
//            map.get(key).finish();
            iterator.remove();
        }
    }

    @SuppressLint("NewApi")
    public static void finishActivity(Class<? extends Activity> class1) {
        if (App.activityMap.get(class1.getSimpleName()) != null) {
            App.activityMap.get(class1.getSimpleName()).finish();
            App.activityMap.remove(class1.getSimpleName());
        }
    }

    public static void removeActivity(Class<? extends Activity> class1) {
        if (App.activityMap.get(class1.getSimpleName()) != null) {
            App.activityMap.remove(class1.getSimpleName());
        }
    }

    public static void exitOther(Activity activity) {
        Set<Map.Entry<String, Activity>> entries = App.activityMap.entrySet();
        Iterator<Map.Entry<String, Activity>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Activity> next = iterator.next();
            try {
                if (!activity.getClass().getSimpleName().equals(next.getKey()))
                    next.getValue().finish();
                else App.activityMap.put(activity.getClass().getSimpleName(), activity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static int runningNumber() {
        return App.activityMap.size();
    }

    public static boolean isExist(Class<? extends Activity> class1) {
        return App.activityMap.get(class1.getSimpleName()) == null;
    }
}
